package com.googlecode.spruce.web.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.googlecode.spruce.dao.HostDao;
import com.googlecode.spruce.dao.ServiceGroupDao;
import com.googlecode.spruce.dao.ServiceGroupScheduleDao;
import com.googlecode.spruce.domain.Host;
import com.googlecode.spruce.domain.ServiceGroup;
import com.googlecode.spruce.domain.ServiceGroupSchedule;
import com.googlecode.spruce.schedule.ScheduledRemotePluginService;

@Controller
@RequestMapping("/admin/schedule")
public class ServiceGroupScheduleDashboard
{
    @Autowired
    private ServiceGroupScheduleDao seviceGroupScheduleDao;

    @Autowired
    private ServiceGroupDao serviceGroupDao;

    @Autowired
    private HostDao hostDao;

    @Autowired
    private ScheduledRemotePluginService scheduler;

    @RequestMapping(value = "/index.html", method = RequestMethod.GET)
    public ModelAndView getAll()
    {
        final ModelAndView model = new ModelAndView("schedule/index");

        final List<ServiceGroup> serviceGroups = this.serviceGroupDao.getAll();
        final List<Host> hosts = this.hostDao.getAll();
        final List<ServiceGroupSchedule> schedules = this.seviceGroupScheduleDao.getAll();

        model.addObject("serviceGroups", serviceGroups);
        model.addObject("hosts", hosts);
        model.addObject("schedules", schedules);

        return model;
    }

    @RequestMapping(value = "/add.do", method = RequestMethod.POST)
    public ModelAndView add(@RequestParam("schedule") String schedule, @RequestParam("sgid") Integer serviceGroupID,
            @RequestParam("hostid") Integer hostID)
    {
        final ServiceGroup seviceGroup = this.serviceGroupDao.findByID(serviceGroupID);
        final Host host = this.hostDao.findByID(hostID);

        final ServiceGroupSchedule serviceGroupSchedule = new ServiceGroupSchedule();

        serviceGroupSchedule.setCron(schedule);
        serviceGroupSchedule.setHost(host);
        serviceGroupSchedule.setServiceGroup(seviceGroup);

        this.seviceGroupScheduleDao.save(serviceGroupSchedule);

        this.scheduler.schedule(serviceGroupSchedule);

        return getAll();
    }
}
